package com.hainatong.mvvmbase.http.interceptor;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;

import java.io.*;
import java.nio.charset.Charset;

public class CustomGsonResponseBodyConverter<T> implements Converter<ResponseBody, T>
{
    private final Gson gson;

    private final TypeAdapter<T> adapter;

    private static final Charset UTF_8 = Charset.forName("UTF-8");

    CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter)
    {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value)
            throws IOException
    {
        //这里处理 请求返回的 字符串 转化为 json对象的
        //这里 也可以 统一处理 错误码
        //把responsebody转为string
        String response = value.string();
        //LogUtil.e("CustomGsonResponseBodyConverter","response = " +  response);
        /*
        //登录请求 返回 一个 非json 字符串
        if( !GsonUtil.isJson( response ))
        {
            response = GsonUtil.toJson( response );
        }
        else
        {
            // 这里只是为了检测code是否==0,所以只解析HttpStatus中的字段,因为只要code和message就可以了
            HttpStatus httpStatus = gson.fromJson(response, HttpStatus.class);
            if (httpStatus.isCodeInvalid())
            {
                value.close();
                //抛出一个RuntimeException, 这里抛出的异常会到 Observer 的onError()方法中统一处理
                throw new ApiException(httpStatus.getCode(), httpStatus.getMessage());
            }
        }
        */


        MediaType contentType = value.contentType();
        Charset charset = contentType != null ? contentType.charset(UTF_8) : UTF_8;
        InputStream inputStream = new ByteArrayInputStream(response.getBytes());
        Reader reader = new InputStreamReader(inputStream, charset);
        JsonReader jsonReader = gson.newJsonReader(reader);

        //JsonReader jsonReader = gson.newJsonReader(value.charStream());
        try
        {
            T result = adapter.read(jsonReader);
            if (jsonReader.peek() != JsonToken.END_DOCUMENT)
            {
                throw new JsonIOException("JSON document was not fully consumed.");
            }
            return result;
        }
        finally
        {
            value.close();
        }
    }
}
